﻿using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq;

namespace JTTD.Extensions
{
    public class AuthResponsesOperationFilter : IOperationFilter
    {
        public void Apply(Operation operation, OperationFilterContext context)
        {
            //获取是否添加登录特性
            var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
             .Union(context.MethodInfo.GetCustomAttributes(true))
             .OfType<TypeFilterAttribute>().Any();

            var unAuthAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
             .Union(context.MethodInfo.GetCustomAttributes(true))
             .OfType<UnAuthorize>().Any();

            if (authAttributes && !unAuthAttributes)
            {
                operation.Responses.Add("401", new Response { Description = "暂无访问权限" });
                operation.Responses.Add("403", new Response { Description = "禁止访问" });
                operation.Security = new List<IDictionary<string, IEnumerable<string>>>
                {
                    new Dictionary<string, IEnumerable<string>> {{ "Bearer", new[] { "jttdApi" } }}
                };
            }
        }
    }
}
